package com.healthdata.filter;

import com.healthdata.service.UserService;
import com.healthdata.util.JwtUtil;
import com.healthdata.util.ResponseUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserService userService;

    public JwtAuthenticationFilter(JwtUtil jwtUtil, UserService userService) {
        this.jwtUtil = jwtUtil;
        this.userService = userService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        final String authHeader = request.getHeader("Authorization");
        String token = null;

        // 支持不带Bearer的情况
        if (authHeader != null) {
            if (authHeader.startsWith("Bearer ")) {
                token = authHeader.substring(7);
            } else {
                token = authHeader; // 直接使用整个Authorization头作为token
            }
        }

        if (token == null) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            final Long userId = jwtUtil.getUserIdFromToken(token);

            if (userId != null && jwtUtil.verifyToken(token)) {
                com.healthdata.entity.User user = userService.getById(userId);

                if (user != null) {
                    UserDetails userDetails = new User(
                            user.getUsername(),
                            user.getPassword(),
                            Collections.singletonList(() -> user.getRole())
                    );

                    UsernamePasswordAuthenticationToken authToken =
                            new UsernamePasswordAuthenticationToken(
                                    userDetails,
                                    null,
                                    userDetails.getAuthorities());
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                }
            } else {
                ResponseUtil.sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token 无效或已过期");
                return;
            }
        } catch (Exception e) {
            ResponseUtil.sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token 验证失败");
            return;
        }

        filterChain.doFilter(request, response);
    }
}